package org.micropayment.model.service.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.micropayment.model.ProviderResource;
import org.micropayment.model.service.ProviderResourceDAO;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 *
 * @author jj
 */
@Repository("providerDao")
public class JpaProviderResourceDAO implements ProviderResourceDAO {

    private static Logger logger =
            LoggerFactory.getLogger(JpaProviderResourceDAO.class);

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
   
    public ProviderResource findById(String id) {
        return entityManager.find(ProviderResource.class, id);
    }

    public List<ProviderResource> findAll() {
        Query query =
                entityManager.createNamedQuery("ProviderResource.findAll");
        List<ProviderResource> providers  = query.getResultList();
        return providers;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public ProviderResource save(ProviderResource provider) {
        entityManager.persist(provider);
        entityManager.flush();
        return provider;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public ProviderResource update(ProviderResource provider) {
        entityManager.merge(provider);
        entityManager.flush();
        return provider;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public boolean delete(ProviderResource provider) {
        provider = entityManager.getReference(ProviderResource.class, provider.getId());
        if (provider == null) return false;
        entityManager.remove(provider);
        entityManager.flush();
        return true;
    }

    public List<ProviderResource> findList(int firstResult, int maxResults) {
        Query query = entityManager.createQuery(
                "SELECT p FROM ProviderResource p");
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        List<ProviderResource> providers = query.getResultList();
        return providers;
    }


}
